var mongodb = require('mongodb');
var server = new mongodb.Server('127.0.0.1', 27017, {});

var client = new mongodb.Db('mydatabase', server, {w: 1});

/**
 * 访问mongoDB集合
 */ 
client.open(function(err) {
  if (err) throw err;
  client.collection('test_insert', function(err, collection) {
    if (err) throw err;
    // 把MogoDB查询代码放在这里
    /**
     * 将文档插入集合中
     */
    collection.insert(
      { 
        "title": "I like cake",
        "body": "It is quite good."
      },
      {safe: true}, // 安全模式表明数据库操作应该在回调执行之前完成
      function(err, documents) {
        if (err) throw err;
        console.log('Document ID is: ' + documents[0]);
      }
    );
   
    /**
     * 更新MongoDB文档
     */
    var _id = new client.bson_serializer.ObjectID('55b75d6ad00470c80ea892b0');

    collection.update(
      {_id: id},
      {$set: {"title": "I ate too much cake"}},
      {safe: true},
      function(err) {
        if (err) throw err;
      }
    )
   
    /**
     * 搜索文档
     */ 
    collection.find({"title": "I like cake"}).toArray(
      function(err, results) {
        if (err) throw err;
        console.log(results);
      }
    );

    /**
     * 删除文档
     */
    var _id = new client.bson_serializer.ObjectID('55b75d6ad00470c80ea892b0');
    collection.remove({_id: _id}, {safe: true}, function(err){
      if (err) throw err;
    });
  });
});
